package com.daoliuhe.scaffold.filter;

import com.daoliuhe.scaffold.model.User;
import com.daoliuhe.scaffold.service.UserService;
import com.daoliuhe.scaffold.tools.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 记住我
 * @author 21829
 * @date 2016年8月4日
 */
@Resource
public class RememberMeFilter implements Filter {
	
	private static final Logger logger = LoggerFactory.getLogger(RememberMeFilter.class);
	
	@Resource
	private UserService userService;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession(false);
		HttpServletRequest httpReq = (HttpServletRequest) request;
		HttpServletResponse httpResp = (HttpServletResponse) response;
		//是否记住我
		boolean isRemembered = subject.isRemembered();
		//如果记住密码
		if (isRemembered) {
			Object userInfo = session.getAttribute(Constants.USERINFO);
			logger.info("userInfo:{}", userInfo);
			//没有用户信息
			if (null == userInfo) {
				User loginUser = userService.getUserByLoginId(subject.getPrincipal().toString());
				logger.info("loginUser:{}", loginUser);
				if (null == loginUser) {
					subject.logout();
					httpResp.sendRedirect(httpReq.getContextPath() + "/login");
					return;
				} else if (Constants.DISABLE.equalsIgnoreCase(loginUser.getEnabled())) {//用户在vmp中被禁用
					subject.logout();
					httpResp.sendRedirect(httpReq.getContextPath() + "/login");
					return;
				} else {
					subject.login(new UsernamePasswordToken(loginUser.getLoginId(), "0", true));
					session.setAttribute(Constants.USERINFO, loginUser);
					String ip = httpReq.getHeader("x-forwarded-for");
					session.setAttribute(Constants.USER_IP, ip);
					SavedRequest savedRequest = WebUtils.getSavedRequest(request);
					logger.info("savedRequest:{}", savedRequest);
					if (null == savedRequest) {
						
					} else {

					}
				}
			}
		} /*else if (!subject.isAuthenticated()) {
			httpResp.sendRedirect(httpReq.getContextPath() + "/login");
			return;
		}*/
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
